package com.dc.dbus.transport.netty.server;

import java.util.concurrent.ConcurrentHashMap;

import com.dc.dbus.transport.commons.ClientSideDisconnectException;

import com.dc.dbus.transport.netty.Log;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;

public class ClientChannelCenter {

	protected final ConcurrentHashMap<String, Channel> clientNameMapChannel = new ConcurrentHashMap<String, Channel>();
	
	public void clientActive(ChannelId channelId, Channel channel, String address) {

		Log.nettyLinkLogger.info("ClientChannelCenter.clientActive：" + address);
		clientNameMapChannel.put(address, channel);
	}

	public void clientDisconnect(ChannelId channelId, Channel channel, String address) {

		Log.nettyLinkLogger.error("ClientChannelCenter.clientDisconnect：" + address);
		clientNameMapChannel.remove(address);
	}
	
	public void sendToClient(String clientName, Object param) throws ClientSideDisconnectException {
		
		Channel channel = clientNameMapChannel.get(clientName);
		if (channel == null) {
			throw new ClientSideDisconnectException();
		}
		
		channel.writeAndFlush(param);
		
		
		// 测试代码
//		try {
//			channel.disconnect().sync();
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
	}
}
